<template>
  <div class="admin-container">
    <el-container>
      <!-- 主内容区 -------------------------------------------->
      <el-main class="admin-main" style="margin: 0 auto; max-width: 1200px;">
        <div v-if="currentView === 'userInfo'" class="management-section">
          <el-card>
            <!-- 用户信息展示 -->
            <div class="user-info-display">
              <div class="info-item">
                <span class="info-label">用户ID：</span>
                <span class="info-value">{{ userForm.id }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">真实姓名：</span>
                <span class="info-value">{{ userForm.userTrueName }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">手机号：</span>
                <span class="info-value">{{ userForm.userPhoneNumber }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">身份证号：</span>
                <span class="info-value">{{ userForm.userIdNumber }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">邮箱：</span>
                <span class="info-value">{{ userForm.userEmail }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">头像：</span>
                <img v-if="userForm.userPhoto" :src="userForm.userPhoto" class="avatar-display" />
              </div>
              <div class="action-buttons">
                <el-button type="primary" @click="dialogVisible = true">编辑用户信息</el-button>
                <el-button type="warning" @click="showChangePasswordDialog = true">修改密码</el-button>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 编辑用户信息的dialog ---------------------------------------->
        <el-dialog v-model="dialogVisible" title="编辑用户信息" width="50%">
          <el-form 
            :model="userForm" 
            label-width="120px" 
            :rules="rules"
            ref="userFormRef"
          >
            <el-form-item label="用户ID">
              <el-input v-model="userForm.id" disabled />
            </el-form-item>
            
            <el-form-item label="真实姓名" prop="userTrueName">
              <el-input v-model="userForm.userTrueName" />
            </el-form-item>
            <el-form-item label="手机号" prop="userPhoneNumber">
              <el-input v-model="userForm.userPhoneNumber" />
            </el-form-item>
            <el-form-item label="身份证号">
              <el-input v-model="userForm.userIdNumber" />
            </el-form-item>
            <el-form-item label="邮箱" prop="userEmail">
              <el-input v-model="userForm.userEmail" type="email" />
            </el-form-item>
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="http://10.32.82.220:8090/group1/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="userForm.userPhoto" :src="userForm.userPhoto" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">保存</el-button>
              <el-button @click="resetForm">重置</el-button>
              <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

        <!-- 修改密码的对话框 ----------------------------------------------->
        <el-dialog v-model="showChangePasswordDialog" title="修改密码" width="30%">
          <el-form :model="passwordForm" label-width="100px" :rules="passwordRules" ref="passwordFormRef">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showChangePasswordDialog = false">取消</el-button>
            <el-button type="primary" @click="changePassword">确认</el-button>
          </template>
        </el-dialog>

       
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'

// dialog显示控制-----------------------------------------------
const dialogVisible = ref(false)
import { 
  User,
  Document,
  Goods,
  DataAnalysis,
  Calendar,
  Lock,
  UserFilled,
  Plus
} from '@element-plus/icons-vue'
import router from '@/router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { store } from '@/common/store'

// 当前视图
const currentView = ref('userInfo')

// 导航栏映射-------------------------------------------------
const moduleTitles = {
  userManagement: '用户管理',
  newsManagement: '资讯管理',
  productView: '商品界面',
  productData: '商品数据管理',
  appointment: '预约管理',
  auth: '权限管理',
  userInfo: '个人信息修改'
}

const userForm2 = reactive([])
// 点击修改密码后的弹出的窗口--------------------------------------
const showChangePasswordDialog = ref(false)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const userForm3 = ref([])


const userForm = reactive({
  id: '',
  
  userTrueName: '',
  userPhoneNumber: '',
  userIdNumber: '',
  userPhoto: '',
  userEmail: ''
})



// 修改密码验证规则------------------------------------------------------
const passwordRules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value !== passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ]
})

const rules = reactive<FormRules>({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  userTrueName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  userPhoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ],
  userEmail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ]
})

// 表单引用
const userFormRef = ref<FormInstance>()

// 图片上传成功处理
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  userForm.userPhoto = response
}

// 图片上传前验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt5M) {
    ElMessage.error('头像图片大小不能超过 5MB!')
  }

  return isImage && isLt5M
}

// 修改密码函数---------------------------------------------
const changePassword = async () => {
  try {
    const token = localStorage.getItem('adminToken') || ''

    let userData = {
        id: '',
        userName: '',
        userTrueName: '',
        userPhoneNumber: '',
        userIdNumber: '',
        userPhoto: '',
        userEmail: ''
     }
    userData = await getUserID()
    const userName = userData.userName
    if (!userName) {
      ElMessage.error('无法获取用户名')
      return
    }
    
    const res = await axios.put('/tUserInfo/updateUserPassword', null, {
      params: {
        "userName": userName,
        "oldPassword": passwordForm.oldPassword,
        "newPassword": passwordForm.newPassword
      },
      headers: {
        Authorization: `Bearer ${token}`
      }
    })

    if (res.data.code === 200) {
      ElMessage.success('修改密码成功')
      showChangePasswordDialog.value = false
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      ElMessage.error(res.data.message || '修改密码失败')
    }
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('修改密码失败: ' + error.message)
    }
  }
}

// 获取用户信息--------------------------------------------------------------------
const fetchUserInfo = async () => {
  try {
    const token = localStorage.getItem('adminToken') || ''
    let userData = await getUserID()
    const userName = userData.userName

    const res = await axios.get('/tUserInfo/selectById', {
      params: { userName },
      headers: { Authorization: `Bearer ${token}` }
    })
    
    userForm3.value = res.data.data.map(user => ({
        id: user.id,
        userName: user.userName,
        password: user.password, // 添加密码字段
        userTrueName: user.userTrueName,
        userPhoneNumber: user.userPhoneNumber,
        userEmail: user.userEmail,
        userIdNumber: user.userIdNumber,
        userPhoto: user.userPhoto,
        createTime: user.createTime
      }))
      console.log(userForm3.value)
    // 更新userForm数据
    if (userForm3.value.length > 0) {
      const userData = userForm3.value[0]
      userForm.id = userData.id
      userForm.userTrueName = userData.userTrueName
      userForm.userPhoneNumber = userData.userPhoneNumber
      userForm.userIdNumber = userData.userIdNumber
      userForm.userEmail = userData.userEmail
      userForm.userPhoto = userData.userPhoto
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}



const getUserID = async () => {
  try {
    const token = localStorage.getItem('adminToken') || ''
    const response = await axios.post('/tUserInfo/getUserInfo', {}, {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })
    return response.data
  } catch (error) {
    ElMessage.error('获取用户ID失败')
    throw error
  }
}

// 用户信息编辑的提交表单
const submitForm = async () => {
  try {
    const token = localStorage.getItem('adminToken') || ''
    let userData = {
        id: '',
        userName: '',
        userTrueName: '',
        userPhoneNumber: '',
        userIdNumber: '',
        userPhoto: '',
        userEmail: ''
     }
    userData = await getUserID()
    userForm.id = userData.id

    await axios.post('/tUserInfo/modifyUserInfo', userForm, {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })
    
    ElMessage.success('修改成功')
    dialogVisible.value = false
    fetchUserInfo()
  } catch (error) {
    ElMessage.error('修改失败')
  }
}

// 重置用户信息编辑表单
const resetForm = () => {
  userFormRef.value?.resetFields()
  fetchUserInfo()

}

// 退出登录
const logout = () => {
  localStorage.removeItem('adminToken')
  sessionStorage.removeItem('token')
  sessionStorage.removeItem('userinfo')
  store.logined = false
  store.userinfo = {id:"",username:"",name:""}
  store.token = ""
  router.push('/login')
}

// 初始化获取用户数据
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.admin-container {
  height: 100vh;
  display: flex;
  position: relative;
  overflow: auto;
}

.logout-container {
  padding: 10px;
  text-align: center;
  border-bottom: 1px solid #1565c0;
}

.logout-btn {
  width: 90%;
  margin-bottom: 10px;
}

.admin-sidebar {
  background-color: #1e88e5;
  height: 100vh;
}

.admin-menu {
  border-right: none;
}

.admin-main {
  padding: 20px;
  background-color: #f5f7fa;
}

.module-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80vh;
}

.module-placeholder h2 {
  color: #1e88e5;
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}

/* 用户信息展示样式 */
.user-info-display {
  padding: 20px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-label {
  font-weight: bold;
  width: 100px;
  color: #606266;
}

.info-value {
  flex: 1;
  color: #303133;
}

.avatar-display {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  object-fit: cover;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>
